package com.lagou.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.apache.commons.lang.StringUtils;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {

    //秘钥
    private static final String SECRET = "JKKLJOoasdlfj";
    private static final int calendarField = Calendar.DATE;
    private static final String user_id_field = "email";

    /**
     * token 过期时间: 30天
     */
    private static final int expireDays = 20;

    /**
     * 生成 token
     *
     * @param email
     * @return
     */
    public static String createToken(String email) {
        Date iatDate = new Date();
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(calendarField, expireDays);
        //过期时间
        Date expiresDate = nowTime.getTime();

        // header Map
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");


        String token = JWT.create().withHeader(map)
                .withClaim(user_id_field, email)//用户id
                .withIssuedAt(iatDate) // 验签时间
                .withExpiresAt(expiresDate) // 过期时间
                .sign(Algorithm.HMAC256(SECRET)); // 签名

        return token;
    }

    /**
     * 解密Token
     *
     * @param token
     * @return
     */
    private static Map<String, Claim> verifyToken(String token) {
        DecodedJWT jwt = null;
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        jwt = verifier.verify(token);
        return jwt.getClaims();
    }

    /**
     * 根据Token获取用户信息
     *
     * @param token
     * @return
     */
    public static String getUserInfo(String token) {
        Map<String, Claim> claims = verifyToken(token);
        Claim user_id_claim = claims.get(user_id_field);
        if (null == user_id_claim || StringUtils.isEmpty(user_id_claim.asString())) {
            return null;
        }
        return user_id_claim.asString();
    }


}
